const { resolve } = require('path')
const { readdir, stat } = require('fs')

const resolvePath = resolve

async function searchComs(dir, paths=[], coms =[]) {
  await new Promise((resolve, reject) => {
    readdir(dir, async (err, files) => { 

      if(!err) {
        await Promise.all(
          files.map(async fileName => {
            if(/^index\.(ts|js)x?$/.test(fileName)) {
              const com = addCom(dir, paths)
  
              if(com) {
                com.hasXml = await existXml(dir)
                com.hasStatic = await existStatic(dir)
                com.hasFreeLayoutXml = await existFreeLayoutXml(dir)
                coms.push(com)
              }
            } else {
              const fullPath = resolvePath(dir, fileName)
    
              await searchComs(fullPath, [...paths, fileName], coms)
            }
          })
        )
        
      }

      resolve(coms)
    })
  })

  return coms
}

function existXml(dir) {
  return new Promise((resolve,reject)=> {
    stat(resolvePath(dir, 'config.xml'), (err)=> {
      resolve(!err)
    })
  })
}

function existStatic(dir) {
  return new Promise((resolve,reject)=> {
    stat(resolvePath(dir, 'static'), (err)=> {
      resolve(!err)
    })
  })
}
function existFreeLayoutXml(dir) {
  return new Promise((resolve,reject)=> {
    stat(resolvePath(dir, 'freeLayoutConfig.xml'), (err)=> {
      resolve(!err)
    })
  })
}
function addCom(dir, paths) {
  if(paths.length< 2) {
    return null
  }

  const version = paths[paths.length - 1]
  const name = paths[paths.length - 2]

  if(isNaN(parseInt(version))) {
    return null
  }

  return {
    dir,
    name,
    version
  }
}

module.exports = {
  searchComs
}
